//
//  WeatherViewController.m
//  B
//
//  Created by 王展 on 15/11/5.
//  Copyright © 2015年 wangzhan. All rights reserved.
//

#import "WeatherViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "AFNetworking.h"
#import "TodayWeatherTableViewCell.h"
#import "SevenWeatherTableViewCell.h"
#import "ColdTableViewCell.h"
#import "ClothesTableViewCell.h"
#import "CarTableViewCell.h"
#import "UltravioletTableViewCell.h"
#import "TravellTableViewCell.h"
#import "Today.h"
#import "Seven.h"

#import "MJRefresh.h"
#import "ChineseToPinyin.h"

#import "ColdViewController.h"
#import "ClothesViewController.h"
#import "CarViewController.h"
#import "UltravioletViewController.h"
#import "WzTravellViewController.h"

#import "WeatherSearchViewController.h"
#import "WzCitySearchViewController.h"

@interface WeatherViewController ()<CLLocationManagerDelegate,UITableViewDataSource,UITableViewDelegate,searchViewControllerDelegate,cityVCdelegate>

@property(nonatomic,strong)CLLocationManager *locationManager;
@property(nonatomic,copy)NSString *localCity;

@property(nonatomic,strong)UITableView *weatherTV;

@property(nonatomic,strong)UIImageView *backImageView;
@property(nonatomic,strong)UIImage *backImage;

@property(nonatomic,strong)NSMutableArray *todayArray;
@property(nonatomic,strong)NSMutableArray *sevenArray;

@property(nonatomic,strong)CLLocation *location;

@property(nonatomic,strong)UIImageView *weatherImageView;
@property(nonatomic,strong)UIImage *weatherImage;

@property(nonatomic,assign)float latitude;
@property(nonatomic,assign)float longitude;

@property(nonatomic,assign)BOOL first;
@property(nonatomic,assign)NSInteger getNum;

@property(nonatomic,assign)BOOL search;

@property (nonatomic, strong) UIVisualEffectView *visual;

@end

@implementation WeatherViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:1];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //初始化
    self.weatherImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.first = NO;
    self.getNum = 0;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"热门" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"搜索icon"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction)];
    
    //定位系统!
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager startUpdatingLocation];
    

    [self createWeatherOrdinaryBackView];
    [self createVisualView];
    [self createWeatherView];
    [self addHeaderRefresh];
}

-(void)leftBarButtonAction
{
    WzCitySearchViewController *citySearchVC = [[WzCitySearchViewController alloc] init];
    
    citySearchVC.hidesBottomBarWhenPushed = YES;
    citySearchVC.myAgent = self;
    
    [self.backImageView removeFromSuperview];
    [self.visual removeFromSuperview];
    [self.weatherTV removeFromSuperview];

    [self.navigationController pushViewController:citySearchVC animated:NO];
}

-(void)rightBarButtonAction
{
    WeatherSearchViewController *searchVC = [[WeatherSearchViewController alloc] init];
    
    searchVC.myAgent = self;
    
    searchVC.hidesBottomBarWhenPushed = YES;
    
    [self.backImageView removeFromSuperview];
    [self.visual removeFromSuperview];
    [self.weatherTV removeFromSuperview];

    
    [self.navigationController pushViewController:searchVC animated:NO];
}

-(void)searchCityName:(NSString *)cityName
{
    [self createWeatherOrdinaryBackView];
    [self createVisualView];
    [self createWeatherView];
    [self addSearchCityRefresh:cityName];
}

-(void)searchLeftButtonAction
{
    [self createWeatherOrdinaryBackView];
    [self createVisualView];
    [self createWeatherView];
    [self addHeaderRefresh];
}

-(void)LeftButtonAction
{
    [self createWeatherOrdinaryBackView];
    [self createVisualView];
    [self createWeatherView];
    [self addHeaderRefresh];
}

-(void)giveCityID:(NSString *)cityID
{
    [self createWeatherOrdinaryBackView];
    [self createVisualView];
    [self createWeatherView];
    [self addSearchCityRefresh:cityID];
}

-(void)addSearchCityRefresh:(NSString *)cityName
{
    self.weatherTV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
                [self gettodayData:cityName];
                [self getsevenDayData:cityName];
    }];
    
     [self.weatherTV.header beginRefreshing];
}

//下拉刷新
//设置下拉刷新
-(void)addHeaderRefresh
{
    self.weatherTV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//         进入刷新状态后会自动调用这个block

//                //获取当前城市
//                CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//                CLLocation *location=[[CLLocation alloc] initWithLatitude:vc.latitude longitude:vc.longitude];
//        
//                [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//                    if (placemarks.count == 0 || error) return ;
//                    CLPlacemark *pm = [placemarks firstObject];
//                    vc.localCity = pm.locality;
//        
//                    //将字符串全变成小写字母
//                    NSString *pinyinLocalCity = [ChineseToPinyin pinyinFromChiniseString:vc.localCity];
//                    pinyinLocalCity = [pinyinLocalCity lowercaseString];
//                    pinyinLocalCity = [pinyinLocalCity substringToIndex:[pinyinLocalCity length] - 3];
//        
//                    [vc gettodayData:pinyinLocalCity];
//                    [vc getsevenDayData:pinyinLocalCity];
//                }];
        
                [self gettodayData:@"dalian"];
                [self getsevenDayData:@"dalian"];
    }];
    
    [self.weatherTV.header beginRefreshing];
}

//获取当前经纬度
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    // 1.获取用户位置的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);

    self.location = location;
    self.latitude = coordinate.latitude;
    self.longitude = coordinate.longitude;
    
    // 2.停止定位
    [manager stopUpdatingLocation];
}

//懒加载创建locationManager
-(CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager setDelegate:self];
    }
    
    return _locationManager;
}

//创建天气默认背景页面
-(void)createWeatherOrdinaryBackView
{
    self.backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.backImage = [UIImage imageNamed:@"back"];
    self.backImageView.image = self.backImage;
    [self.view addSubview:self.backImageView];
    
}
//创建对应天气背景页面
-(void)createNowWeatherBackView
{
    self.weatherImageView.image = self.weatherImage;
    [self.backImageView addSubview:self.weatherImageView];
}

//创建天气页面
-(void)createWeatherView
{
    self.weatherTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64 - 49)];
    self.weatherTV.backgroundColor = [UIColor clearColor];
    self.weatherTV.delegate = self;
    self.weatherTV.dataSource = self;
    self.weatherTV.showsVerticalScrollIndicator = NO;
    self.weatherTV.separatorInset = UIEdgeInsetsMake(0, 20 * XWIDTH, 0, 20 * XWIDTH);
    self.weatherTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.weatherTV];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"%ld",_todayArray.count);
    return _todayArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        TodayWeatherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"today"];
        if (nil == cell) {
            cell = [[TodayWeatherTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"today"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.today = [self.todayArray objectAtIndex:0];
        return cell;
    }else if (indexPath.row == 1){
        SevenWeatherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"seven"];
        if (nil == cell) {
            cell = [[SevenWeatherTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"seven"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;  
        }
        cell.sevenArray = self.sevenArray;
        return cell;
    }else if (indexPath.row == 2){
        ColdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cold"];
        if (nil == cell) {
            cell = [[ColdTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cold"];
        }
        return cell;
    }else if (indexPath.row == 3){
        ClothesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"clothes"];
        if (nil == cell) {
            cell = [[ClothesTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"clothes"];
        }
        return cell;
    }else if (indexPath.row == 4){
        CarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"car"];
        if (nil == cell) {
            cell = [[CarTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"car"];
        }
        return cell;
    }else if (indexPath.row == 5){
        UltravioletTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"uv"];
        if (nil == cell) {
            cell = [[UltravioletTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"uv"];
        }
        return cell;
    }else{
        TravellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travell"];
        if (nil == cell) {
            cell = [[TravellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"travell"];
        }
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 580 * XHIGHT;
    } else if (indexPath.row == 1) {
        return 460 * XHIGHT;
    } else{
        return 50 * XHIGHT;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.weatherTV deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 2) {
        ColdViewController *coldVC = [[ColdViewController alloc] init];
        coldVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:coldVC animated:NO];
        coldVC.today = [self.todayArray objectAtIndex:0];
    }else if (indexPath.row == 3){
        ClothesViewController *clothesVC = [[ClothesViewController alloc] init];
        clothesVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:clothesVC animated:NO];
        clothesVC.today = [self.todayArray objectAtIndex:0];
    }else if (indexPath.row == 4){
        CarViewController *carVC = [[CarViewController alloc] init];
        carVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:carVC animated:NO];
        carVC.today = [self.todayArray objectAtIndex:0];
    }else if (indexPath.row == 5){
        UltravioletViewController *ultravioletVC = [[UltravioletViewController alloc] init];
        ultravioletVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:ultravioletVC animated:NO];
        ultravioletVC.today = [self.todayArray objectAtIndex:0];
    }else if (indexPath.row == 6){
        WzTravellViewController *travelVC = [[WzTravellViewController alloc] init];
        travelVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:travelVC animated:NO];
        travelVC.today = [self.todayArray objectAtIndex:0];
    }
}


//淡入淡出效果
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CATransition *transition = [CATransition animation];
    
    /** 2. 设置type类型 */
    transition.type = @"fade";/**< 翻滚效果 */
    
    /** 3. 设置动画属性 */
    transition.duration = 0.7;
    transition.repeatCount = 1;
    
    /** 4. layer添加动画 */
    [cell.layer addAnimation:transition forKey:@"trans"];
}

-(void)createVisualView
{
//    self.visual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
//    _visual.frame = CGRectMake(0, 0, WIDTH, HIGHT);
//    _visual.alpha = 0;
//    [self.view addSubview:_visual];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > 70 *XHIGHT) {
        CGFloat change = scrollView.contentOffset.y;
        self.visual.alpha = 0 + (change / 400 *XHIGHT);
        if (self.visual.alpha > 0.8) {
            self.visual.alpha = 0.8;
        }
    } else if (scrollView.contentOffset.y < 60 *XHIGHT) {
        self.visual.alpha = 0;
    }
}




//获取未来七天天气预报数据
-(void)getsevenDayData:(NSString *)localcity
{
    //检查网络状态管理者 是单例
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"网络状态 = %ld", status);
    }];
    
    NSString *url_string = [NSString stringWithFormat:@"http://api.k780.com:88/?app=weather.future&weaid=%@&&appkey=15444&sign=0ae11d1a1780cbd0d768f016c19a8a1c&format=json",localcity];
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        //        NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        self.sevenArray = [NSMutableArray array];
        [self.sevenArray removeAllObjects];
        NSDictionary *bigDic = responseObject;
        NSMutableArray *array = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in array) {
            Seven *seven = [[Seven alloc] init];
            [seven setValuesForKeysWithDictionary:dic];
            [self.sevenArray addObject:seven];
        }
        
        if (self.getNum != 1) {
            self.getNum++;
        }else if(self.getNum == 1)
        {
//            [self.weatherTV headerEndRefreshing];
            
            [self.weatherTV.header endRefreshing];
            [self.weatherTV reloadData];
            self.weatherTV.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            self.getNum = 0;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
}

//获取当天天气情况数据
-(void)gettodayData:(NSString *)localCity
{
    //检查网络状态管理者 是单例
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"网络状态 = %ld", status);
    }];
    
    NSString *url_string = [NSString stringWithFormat:@"http://api.k780.com:88/?app=weather.today&weaid=%@&&appkey=15444&sign=0ae11d1a1780cbd0d768f016c19a8a1c&format=json",localCity];

    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
//                NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        self.todayArray = [NSMutableArray array];
        [self.todayArray removeAllObjects];
        NSDictionary *bigDic = responseObject;
        NSDictionary *resultDic = [bigDic objectForKey:@"result"];
        Today *today = [[Today alloc] init];
        [today setValuesForKeysWithDictionary:resultDic];
        [self.todayArray addObject:today];
        
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100 * XWIDTH, 40 * XHIGHT)];
        title.text = today.citynm;
        title.font = [UIFont fontWithName:@"HiraKakuProN-W3" size:19];
        [title setTextAlignment:NSTextAlignmentCenter];
        self.navigationItem.titleView = title;
        
        if ([today.weather containsString:@"雨"]) {
            self.weatherImage = [UIImage imageNamed:@"rain"];
            [self createNowWeatherBackView];
        }else if ([today.weather containsString:@"晴"]){
            self.weatherImage = [UIImage imageNamed:@"sun"];
            [self createNowWeatherBackView];
        }else if ([today.weather containsString:@"云"]){
            self.weatherImage = [UIImage imageNamed:@"yun"];
            [self createNowWeatherBackView];
        }else if ([today.weather containsString:@"雪"]){
            self.weatherImage = [UIImage imageNamed:@"snow"];
            [self createNowWeatherBackView];
        }
        else if ([today.weather containsString:@"阴"]){
            self.weatherImage = [UIImage imageNamed:@"yin"];
            [self createNowWeatherBackView];
        }else if ([today.weather containsString:@"霾"]){
            self.weatherImage = [UIImage imageNamed:@"mai"];
            [self createNowWeatherBackView];
        }
        else
        {
            self.weatherImage = [UIImage imageNamed:@"back"];
            [self createNowWeatherBackView];
        }
        
        if (self.getNum != 1) {
            self.getNum++;
        }else if(self.getNum == 1)
        {
//            [self.weatherTV headerEndRefreshing];
            [self.weatherTV.header endRefreshing];
            [self.weatherTV reloadData];
            self.weatherTV.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            self.getNum = 0;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
